package dongze.com.ckdj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.NamePlateActivity;
import dongze.com.ckdj.activity.SelectCheckPointActivity;
import dongze.com.ckdj.adapter.CheckInOperationAdapter;
import dongze.com.ckdj.adapter.TypedListItem;
import dongze.com.ckdj.adapter.VehicleInformationAdapter;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.IRecordRequestBuilder;
import dongze.com.ckdj.data.entity.request.Record;
import dongze.com.ckdj.data.entity.request.RecordOption;
import dongze.com.ckdj.data.entity.request.RecordRequestBody;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.util.MyLog;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;


/**
 * Created by fanqwz on 2017/7/21.
 */

public class CheckInOperationFragment extends ProcessableFragment {
    private static final String TAG = CheckInOperationFragment.class.getSimpleName();
    @BindView(R.id.save_record)
    Button saveBtn;
    @BindView(R.id.record_list)
    ListView mOperationList;
    List<TypedListItem> typedListItems;

    @Inject
    InspectionSectionResponse mInspectionSection;
    @Inject
    VehicleInformationDetail vehicleInformationDetail;
    @Inject
    User user;
    @Inject
    DaoSession daoSession;

    CheckInOperationAdapter checkInOperationAdapter;
    //    Menu menu;
//    boolean canSave = false;
    OnCheckInOperationFinishedListener onCheckInOperationFinishedListener;

    public void setOnCheckInOperationFinishedListener(OnCheckInOperationFinishedListener onCheckInOperationFinishedListener) {
        this.onCheckInOperationFinishedListener = onCheckInOperationFinishedListener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        MyLog.d(TAG, "onCreate: " + this);
        super.onCreate(savedInstanceState);

        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            getFragmentManager().beginTransaction().remove(this).commit();
            return;
        }
    }

    @Nullable
    @Override
    protected View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_check_in_operation, container, false);
        ButterKnife.bind(this, root);

        if (savedInstanceState == null) {
            if (checkInOperationAdapter == null)
                loadOperations();
            else
                mOperationList.setAdapter(checkInOperationAdapter);
        }

        return root;
    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        super.onCreateOptionsMenu(menu, inflater);
//        inflater.inflate(R.menu.check_in_operation, menu);
//        this.menu = menu;
//        menu.findItem(R.id.save_record).setEnabled(canSave);
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.save_record) {
            saveRecord(null);
        }
//        else if (item.getItemId() == R.id.name_plat) {
//            onNamePalteBtnClick(null);
//        }
        else if (item.getItemId() == R.id.mass_loss_record) {
            onMassLossBtnClick(null);
        } else {
            return super.onOptionsItemSelected(item);
        }

        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnClick(R.id.mass_loss_btn)
    void onMassLossBtnClick(View view) {
        SelectCheckPointActivity.actionStart(getActivity(), vehicleInformationDetail.getVoyage(), vehicleInformationDetail.getType(), "", "");
    }

    @OnClick(R.id.name_plat_btn)
    void onNamePalteBtnClick(View view) {
        Intent intent = new Intent(getContext().getApplicationContext(), NamePlateActivity.class);
        intent.putExtra("vin", vehicleInformationDetail.getVin());
        startActivity(intent);

//        resume的时候状态不能恢复，不能用下面方式
//        NamePlateFragment fragment = new NamePlateFragment();
//        fragment.setListener(new NamePlateFragment.OnOulineOKListener() {
//            @Override
//            public void onOutLineOK(String uri) {
//                getActivity().getSupportFragmentManager().popBackStack();
//            }
//        });
//        getActivity().getSupportFragmentManager()
//                .beginTransaction()
//                .replace(R.id.fragment_container, fragment)
//                .addToBackStack("1234")
//                .commit();
//        getChildFragmentManager().saveFragmentInstanceState(this);
    }

    @OnClick(R.id.save_record)
    void saveRecord(View view) {
        MyLog.d(TAG, "saveRecord: ");
        if (checkOperationLoaded()) {
            final RecordRequestBody recordRequestBody = new RecordRequestBody();
            Record record = new Record();
            record.setType("1"/*附件*/);
            record.setBrand_code(vehicleInformationDetail.getBrand_code());
            record.setBrand_name(vehicleInformationDetail.getBrand_name());
            record.setVin(vehicleInformationDetail.getVin());
            record.setUser_no(user.getUser_no());
            record.setUser_name(user.getUser_name());
            record.setNode_code(mInspectionSection.getNode_code());
            record.setNode_name(mInspectionSection.getNode_name());
            recordRequestBody.setRecord(record);
            ((IRecordRequestBuilder) mOperationList.getAdapter()).build(recordRequestBody)
                    .subscribe(new Consumer<RecordRequestBody>() {
                        @Override
                        public void accept(RecordRequestBody recordRequestBody) throws Exception {
                            mapUtil.addRecord(recordRequestBody, new DisposableObserver<String>() {

                                @Override
                                protected void onStart() {
                                    super.onStart();
                                    doProcessing();
                                }

                                @Override
                                public void onNext(String value) {
                                    finishProcessing();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    e.printStackTrace();
                                    finishProcessing();
                                    new AlertDialog.Builder(getContext())
                                            .setTitle("错误")
                                            .setMessage("保存记录失败：" + e.getMessage())
                                            .create()
                                            .show();
                                }

                                @Override
                                public void onComplete() {
                                    mOperationList.setAdapter(null);

//                    if (menu != null) {
//                        canSave = false;
//                        MenuItem item = menu.findItem(R.id.save_record);
//                        if (item != null)
//                            item.setEnabled(false);
//                    }

                                    if (onCheckInOperationFinishedListener != null)
                                        onCheckInOperationFinishedListener.onCheckInOperationFinished();

                                    if (typedListItems != null) {
                                        VehicleInformationAdapter adapter = new VehicleInformationAdapter();
                                        TypedListItem[] arr = new TypedListItem[typedListItems.size()];
                                        typedListItems.toArray(arr);
                                        adapter.setListItems(arr);
                                        mOperationList.setAdapter(adapter);
                                    }

                                    saveBtn.setEnabled(false);
//                            getActivity().setResult(Activity.RESULT_OK);
//                            getActivity().finish();
                                }
                            });
                        }
                    });
        }
    }

    private boolean checkOperationLoaded() {
        if (mOperationList.getAdapter() == null) {
            new AlertDialog.Builder(getContext())
                    .setTitle("错误")
                    .setMessage("请先选择点检环节")
                    .create()
                    .show();
            return false;
        } else if (mOperationList.getAdapter() instanceof CheckInOperationAdapter) {
            return true;
        } else {
            return false;
        }
    }

    private void loadOperations() {
        if (mInspectionSection == null || vehicleInformationDetail == null)
            return;

        MyLog.d(TAG, "loadOperations: " + mInspectionSection);
        doProcessing();
        mapUtil.getOperations(
                vehicleInformationDetail.getVin(),
                mInspectionSection.getNode_code(),
                new DisposableObserver<List<TypedListItem>>() {
                    @Override
                    public void onNext(List<TypedListItem> value) {
//                        for (TypedListItem t :
//                                value) {
//                            for (int i = 0; i < vehicleInformationDetail.getVin_info().size(); i++) {
//                                if (TextUtils.equals(vehicleInformationDetail.getVin_info().get(i).getKey(), t.getKey())) {
//                                    t.setValue(vehicleInformationDetail.getVin_info().get(i).getValue());
//                                    break;
//                                }
//                            }
//                        }
                        typedListItems = value;
                        checkInOperationAdapter = new CheckInOperationAdapter(getActivity(), daoSession, value, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                onMassLossBtnClick(v);
                            }
                        });
                        mOperationList.setAdapter(checkInOperationAdapter);
                    }

                    @Override
                    public void onError(Throwable e) {
                        MyLog.e(TAG, "onError: ", e);
                        new AlertDialog.Builder(getActivity())
                                .setTitle(e.getCause() == null ? "" : e.getCause().toString())
                                .setMessage(e.getMessage())
                                .create()
                                .show();
                        if (getView() != null)
                            getView().setEnabled(false);
                        finishProcessing();

                        if (onCheckInOperationFinishedListener != null)
                            onCheckInOperationFinishedListener.onCheckInOperationFinished();

                        saveBtn.setEnabled(false);
                    }

                    @Override
                    public void onComplete() {
                        finishProcessing();

                        if (typedListItems == null || typedListItems.size() == 0)
                            saveBtn.setEnabled(false);
//                        if (menu != null) {
//                            canSave = true;
//                            MenuItem item = menu.findItem(R.id.save_record);
//                            if (item != null)
//                                item.setEnabled(true);
//                        }
                    }
                });
    }

    public interface OnCheckInOperationFinishedListener {
        void onCheckInOperationFinished();
    }
}
